import { Modal, message, Upload, Form, Row, Col, Tree, Input, TreeSelect } from "antd";
import React, { useImperativeHandle, useState } from "react";
import { InboxOutlined } from '@ant-design/icons';
import { imageLibraryApi as api } from "@/api";
import styles from "./styles.module.scss"
import { getSTStoken, uploadFileWithProgress, getOSSClient } from "./service";
import { globalModal } from "@/data";
const { Dragger } = Upload;



const XxAliOssUploadModal = ({ onRef, onUploadSuccess, accept = ".jpg,.png,.jepg,.gif" }) => {
    const [loadingUpload, setLoadingUpload] = useState(false);

    const [fileList, setFileList] = useState([]);
    const [form] = Form.useForm();
    const [show, setShow] = useState(false);
    const [dirTree, setDirTree] = useState([]);
    const [loadingDir, setLoadingDir] = useState(true);


    const getDir = async () => {
        try {
            setLoadingDir(true);
            const { data, code, msg } = await api.queryDir();
            setDirTree(data);
        } catch (error) {
            message.error(msg);
        } finally {
            setLoadingDir(false)
        }
    }


    const close = () => {
        setShow(false);

    }


    const open = () => {
        setShow(true)
        getDir()
    }

    useImperativeHandle(onRef, () => ({
        open: open
    }))


    const uploadFile = async (file, prefix, count = Number) => {
        try {
            setLoadingUpload(true);
            const config = await getSTStoken();
            const client = getOSSClient(config);
            //multipartUpload 分片上传
            const result = await client.multipartUpload(`${prefix}${file.name}`, file, {
                progress: (p, checkpoint) => {
                    console.log(`上传进度: ${Math.floor(p * 100)}%`);
                    // 保存断点信息，用于断点续传
                    // localStorage.setItem('uploadCheckpoint', JSON.stringify(checkpoint));
                },
            });

            console.log('上传成功:', result);
            count++;
            // setFileList(fileList.map(item => {
            //     if (item.uid === file.uid) {
            //         return { ...item, status: 'done' }
            //     } else {
            //         return item;
            //     }

            // }))
            return true;
            // setShow(false)
            // modal.success({
            //     centered: true,
            //     title: "提示",
            //     content: "上传成功"
            // });
            // onUploadSuccess()
        } catch (error) {
            console.log("上传失败原因：", error);
            // modal.error({
            //     centered: true,
            //     title: "提示",
            //     content: "上传失败"
            // });
        } finally {
            // setLoadingUpload(false);
        }
    }



    //校验成功就上传吧
    const onUpload = async ({ prefix }) => {
        try {
            let count = 0;
            //自定义上传
            // fileList.forEach(file => {
            //     console.log("遍历每个文件：\n", file);

            // })
            for (let i = 0; i < fileList.length; i++) {
                const file = fileList[i]
                const res = await uploadFile(file, prefix, count)
                if (res) count++
                if (count >= fileList.length) {
                    console.log("全部上传完成");
                    setLoadingUpload(false);
                    setShow(false)
                    message.success("上传成功")
                    onUploadSuccess & onUploadSuccess()
                    setFileList([])
                }
            }

        } catch (error) {

        }

    }



    const formValidateCheck = () => {
        form.validateFields().then(values => {
            const { prefix } = values;
            onUpload({ prefix });

        }).catch(error => {
            console.log("表单校验失败", error)
        })



    }



    const customRequest = async (options) => {

        // 由于我们已经在handleUpload中处理了文件上传，所以这里不需要做任何事情
        // 可以选择返回一个Promise来模拟上传进度或结果
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve({
                    status: 'done',
                    message: 'Custom upload handled',
                });
            }, 0);
        });
    };

    const props = {
        name: 'file',
        multiple: true,
        action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
        onChange(info) {

            const { status } = info.file;
            if (status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (status === 'done') {
                message.success(`${info.file.name} file uploaded successfully.`);
            } else if (status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
        beforeUpload: (file, waitFiles) => {
            console.log('Before upload', file, waitFiles);
            setFileList([...fileList, ...waitFiles]);
            return false;
        },
        onDrop(e) {
            console.log('Dropped files', e.dataTransfer.files);
        },
        customRequest,
    };
    return (
        <Modal
            title="上传文件"
            width={600}
            open={show}
            onCancel={close}
            centered
            // footer={null}
            okText="开始上传"
            onOk={formValidateCheck}
            confirmLoading={loadingUpload}
        >
            <Form
                form={form}
            >
                <Row gutter={24}>
                    <Col span={24}>
                        <Form.Item rules={[{ required: true, message: '请选择上传目录位置!' }]} name="prefix" label="上传目录位置">
                            <TreeSelect
                                loading={loadingDir}
                                treeData={dirTree}
                                fieldNames={{
                                    label: 'title',
                                    value: 'key',
                                    title: 'title',

                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Dragger
                            {...props}
                            accept={accept}
                            fileList={fileList}
                            rootClassName={styles.custUsedragger}
                        >
                            <p className="ant-upload-drag-icon">
                                <InboxOutlined />
                            </p>
                            <p className="ant-upload-text">点击此处或拖拽至此处上传</p>
                            <p className="ant-upload-hint">
                                支持单个或批量上传，严禁上传公司数据或其他被禁文件
                            </p>
                        </Dragger>
                    </Col>
                </Row>
            </Form>
        </Modal>
    )
}

export default XxAliOssUploadModal;